package org.dragon.advices;

import org.dragon.commons.ApplicationException;
import org.dragon.commons.Errors;
import org.dragon.commons.JsonResult;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

@RestControllerAdvice
public class GlobalRestExceptionAdvice {

    @ExceptionHandler(ApplicationException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Object handleApplicationException(ApplicationException e) {
        return JsonResult.fail(e.getErrors());
    }

    @ExceptionHandler(BindException.class)
    public Object handleBindException(BindException e) {
        return new ResponseEntity<>(
                JsonResult.fail(Errors.BadRequest, Errors.getErrors(e)),
                HttpStatus.BAD_REQUEST);
    }

    @ExceptionHandler({NoHandlerFoundException.class})
    public Object noHandlerFoundExceptionHandle(NoHandlerFoundException e) {
        return new ResponseEntity<>(
                JsonResult.fail(e.getMessage()),
                HttpStatus.NOT_FOUND);
    }

    @ExceptionHandler({HttpRequestMethodNotSupportedException.class})
    public Object httpRequestMethodNotSupportedExceptionHandle(HttpRequestMethodNotSupportedException e) {
        return new ResponseEntity<>(
                JsonResult.fail(Errors.BadRequest, e.getMessage()),
                HttpStatus.BAD_REQUEST);
    }

    @ExceptionHandler(DuplicateKeyException.class)
    public Object duplicateKeyExceptionHandle(DuplicateKeyException e) {
        return new ResponseEntity<>(
                JsonResult.fail(Errors.DuplicateKey, e.getMessage()),
                HttpStatus.BAD_REQUEST);
    }

    @ExceptionHandler(Throwable.class)
    public Object handleThrowable(Throwable e) {
        e.printStackTrace();

        return new ResponseEntity<>(
                JsonResult.fail(e.getMessage()),
                HttpStatus.INTERNAL_SERVER_ERROR);
    }
}